<template>
    <!-- 智能模型集成环境镜像管理 -->
    <div class="model-manage">
        <div class="mm-panel-wrapper-left">
            <Tree ref="leftTreeRef" :isImageManagement="true" :topAdd="true"
                :topAddMenu="right_menuList.rightMenuList_15" :folderMenu="right_menuList.rightMenuList_16"
                :fileMenu="right_menuList.rightMenuList_17" :treeData="ownTreeData" :currentNodeKey="currentNodeKey"
                :defaultExpandedKeys="defaultExpandedKeys" @handleAddNode="handleAddModel"
                @addOrUpdateFolder="handleAddOrUpdateFolder" @nodeClick="nodeClick" @nodeDelete="handleNodeDelete"
                @moveNodeOrder="moveNodeOrder" @handleMenuClick="handleMenuClick">
            </Tree>
        </div>
        <div class="mm-divider"></div>
        <div class="mm-panel-wrapper-right">
            <div class="padding20">
                <div class="mm-panel-title mb-10">
                    镜像基本信息
                    <el-button style="float: right;" class="ml-10" type="primary" @click="handleSave">保存</el-button>
                </div>
                <el-form ref="form" :model="itemForm" :rules="rules" label-width="150px">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="名称" prop="name">
                                <el-input v-model="itemForm.name"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="创建日期" prop="createTime">
                                <el-date-picker v-model="itemForm.createTime" type="date" placeholder="选择日期">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="上传镜像" prop="storagePath">
                                <el-button type="primary" @click="uploadFile">上传</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-form-item label="描述" prop="description">
                        <el-input type="textarea" v-model="itemForm.description"></el-input>
                    </el-form-item>
                </el-form>
                <div class="mm-panel-title mb-10">
                    镜像状态
                </div>
                <el-form ref="form" :model="itemForm" :rules="rules" label-width="150px">
                    <el-form-item label="镜像地址" prop="storagePath">
                        <el-input v-model="itemForm.storagePath" readonly></el-input>
                    </el-form-item>
                    <el-form-item label="镜像大小" prop="fileSize">
                        <el-input v-model="itemForm.fileSize" readonly></el-input>
                    </el-form-item>
                    <el-form-item label="当前阶段" prop="state">
                        <el-input v-model="itemForm.state" readonly></el-input>
                    </el-form-item>
                </el-form>
                <!-- @selection-change="handleSelectionChange" -->
                <!-- <el-table v-loading="loading" :data="tableData">
          <el-table-column label="序号" type="index" width="50" align="center">
            <template slot-scope="scope">
              <span>{{
                (queryParams.pageNum - 1) * queryParams.pageSize +
                scope.$index +
                1
              }}</span>
            </template>
</el-table-column>
<el-table-column label="名称" align="center" prop="imageName" :show-overflow-tooltip="true" width="200" />
<el-table-column label="镜像地址" align="center" prop="imagePath" :show-overflow-tooltip="true" width="200" />
<el-table-column label="镜像仓库路径" align="center" prop="imageRegistryPath" :show-overflow-tooltip="true" width="120" />
<el-table-column label="镜像描述" align="center" prop="imageDescription" :show-overflow-tooltip="true" />
<el-table-column label="创建时间" align="center" prop="createTime" width="160" />
<el-table-column label="操作" align="center" width="80" class-name="small-padding fixed-width">
    <template #default="{ row }">
              <el-dropdown @command="(cmd) => handleCommand(cmd, row)">
                <el-button type="primary">
                  <i class="el-icon-more"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="编辑">编辑</el-dropdown-item>
                  <el-dropdown-item command="删除">删除</el-dropdown-item>
                  <el-dropdown-item command="下载">下载</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
</el-table-column>
</el-table> -->
            </div>
        </div>
        <AddOrUpdateFolder v-if="isAddOrUpdateFolder" ref="addOrUpdateFolderRef" @refresh="getList"></AddOrUpdateFolder>
        <AddOrUpdateModel v-if="isAddOrUpdateModel" ref="addOrUpdateModelRef" @refresh="getList"></AddOrUpdateModel>
    </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { mapState } from "vuex";
import {
    getTreeApi,
    addTreeApi,
    deleteTreeApi,
    updateTreeApi,
    moveTreeApi,
} from "@/api/myspace/preprocessing/index";

import {
    getListApi,
    getListDetailsApi,
    addListApi,
    deleteListApi,
    updateListApi,
    downloadListApi,
} from "@/api/myspace/preprocessing/environmentMirror";

import Tree from "@/components/LeftTree/tree.vue";
import AddOrUpdateModel from "./components/add-or-update-model.vue";
import AddOrUpdateFolder from "./components/add-or-update-folder.vue";

export default {
    data() {
        return {
            itemForm: {
                name: "xxxxxx", //名称
                sampleSetId: 1,
                createTime: "2025-09-01 10:10:10",
                storagePath: "/xxxxx/xxxxxxx", //路径
                description: "xxxxxxxxxxxxxxxxxxxxxx", //描述
                fileSize: "1GB",
                state: "完成",
            },
            rules: {
                name: [{ required: true, message: "名称不可为空", trigger: "blur" }],
            },
            openDialog: false,
            loading: true,
            tableData: [],
            queryParams: {
                // 查询参数
                pageNum: 1,
                pageSize: 10,
                name: "",
                modelId: "",
                folderId: "",
            },
            isAddOrUpdateModel: false, // 是否打开新增数据模型弹框
            isAddOrUpdateFolder: false, // 是否打开创建目录的弹框
            isFolder: false, // 是否展示文件夹详情
            isFile: false, // 是否展示文件详情
            isModel: false, //是否是模型详情
            isModelGroupDetail: false, // 是否展示模型组详情,
            selectedNodeInfo: {}, // 当前选中节点的信息
            ownTreeData: [], // 本账户模型列表
            currentNodeKey: 0, // 当前选中节点的key
            defaultExpandedKeys: [], // 默认展开的节点
            openDialog: false,
            editingRow: null, // 存储正在编辑的行数据
        };
    },
    components: {
        Tree,
        AddOrUpdateModel,
        AddOrUpdateFolder,
    },
    computed: {
        ...mapState({
            right_menuList: (state) => state.modelManageTool.right_menuList,
            selectedNodeId: (state) => state.modelManageTool.model.selectedNodeId,
            expandedNodeIds: (state) => state.modelManageTool.model.expandedNodeIds,
            userId: (state) => state.user.id,
        }),
    },
    async created() {
        await this.getList();
        this.currentNodeKey = this.selectedNodeId;
        this.defaultExpandedKeys = this.expandedNodeIds;
        this.$nextTick(() => {
            this.$refs.leftTreeRef.$refs.treeRef.setCurrentKey(this.currentNodeKey);
            const params = {
                sampleSetId: this.currentNodeKey,
            };
            this.getTableData(params);
        });
    },
    mounted() {
        // 上传文件组件
        this.$EventBus.$on("fileSuccess", (response) => {
            if (response.code != 200) {
                this.$message.error(response.msg);
                return;
            }
            this.$message.success("上传成功");
            this.itemForm.storagePath = response.data.filePath;
            this.itemForm.fileSize = response.data.fileSize;
        });
    },
    methods: {
        uploadFile() {
            this.$EventBus.$emit("openUploader", {
                token: getToken(),
                prefixFlag: 1,
                userId: this.$store.state.user.id,
            });
        },
        // 保存
        handleSave() {

        },
        // 上传文件组件
        uploadBus() {
            // 模拟用户选择的文件
            // const file = new File(["file content"], "filename.txt", { type: "text/plain" });
            // 打开文件选择框
            this.$EventBus.$emit("openUploader", {
                token: getToken(),
                prefixFlag: 1,
                userId: this.userId,
                // fileObject: file
            });
        },
        handleCommand(command, row) {
            switch (command) {
                // case "详情":
                //   break;

                case "编辑":
                    this.editingRow = row;
                    this.openDialog = true;
                    break;
                case "删除":
                    this.delTableData(row);
                    break;

                case "下载":
                    this.downloadTableData(row);
                    break;

                default:
                    break;
            }
        },
        //新增
        handleAdd() {
            this.editingRow = null; // 清空编辑状态
            this.openDialog = true;
        },
        //查询
        handleQuery() {
            this.loading = true;
            const params = {
                sampleSetId: this.currentNodeKey,
                name: this.queryParams.name,
            };
            this.getTableData(params);
        },
        //重置搜索条件
        resetQuery() { },
        async getList(newNodeId) {
            //预处理类型 1=镜像管理，2=在线开发运行，3=算子管理，4=任务流管理
            const params = { preSetType: 1 };
            const res = await getTreeApi(params);
            if (res.code == 200 && Array.isArray(res.data)) {
                this.ownTreeData = res.data[0].commonTreeList;
                const targetId = newNodeId || this.selectedNodeId;
                const targetnode = targetId
                    ? this.recurNodeForTarget(this.ownTreeData, targetId)
                    : this.ownTreeData[0];
                this.nodeClick(targetnode);
            }
        },

        // 表格
        async addSubmit(formData) {
            const api = formData.id
                ? updateListApi // 编辑
                : addListApi; // 新增

            const res = await api(formData);
            if (res.code === 200) {
                this.$message.success(res.msg);
                this.loading = true;
                const params = {
                    sampleSetId: this.currentNodeKey,
                };
                this.getTableData(params);
                this.openDialog = false;
            } else {
                this.$message.error(res.msg);
            }
        },
        async getTableData(params) {
            try {
                const res = await getListApi(params);
                this.tableData = res.rows;
            } catch (error) {
                console.error("获取表格数据失败:", error);
                this.$message.error("数据加载失败，请重试");
            } finally {
                this.loading = false;
            }
        },

        async delTableData(row) {
            const res = await deleteListApi(row.id);
            if (res.code == 200) {
                this.$message.success(res.msg);
            }
        },

        async downloadTableData(row) {
            try {
                const res = await downloadListApi({ imageId: row.id });
                const blob = res.data;
                const header = res.headers["content-disposition"];
                const fileName =
                    this.extractFilename(header) || "perception-sample.zip";
                // 下载
                // const blob = new Blob([res], { type: "application/x-zip-compressed" });
                const downloadUrl = URL.createObjectURL(blob);
                const link = document.createElement("a");
                link.href = downloadUrl;
                link.download = fileName;
                link.style.display = "none";
                document.body.appendChild(link);
                link.click();

                document.body.removeChild(link);
                URL.revokeObjectURL(downloadUrl);
            } catch (error) {
                console.error(error);
            }
        },

        extractFilename(contentDisposition) {
            if (!contentDisposition) {
                return null;
            }

            // 匹配 filename="xxx" （推荐格式，支持包含空格和特殊字符）
            const filenameMatch = contentDisposition.match(
                /filename\s*=\s*"([^"]+)"/i
            );
            if (filenameMatch) {
                return filenameMatch[1];
            }

            // 匹配 filename=xxx （不带引号的简单格式）
            const filenameSimpleMatch = contentDisposition.match(
                /filename\s*=\s*([^;\s]+)/i
            );
            if (filenameSimpleMatch) {
                return filenameSimpleMatch[1];
            }

            return null;
        },

        // 递归获取当前树节点
        recurNodeForTarget(nodeArr, id) {
            for (let i = 0; i < nodeArr.length; i++) {
                if (nodeArr[i].id == id) {
                    return nodeArr[i];
                } else {
                    if (nodeArr[i].children && nodeArr[i].children.length > 0) {
                        let node = this.recurNodeForTarget(nodeArr[i].children, id);
                        if (node) {
                            return node;
                        }
                    }
                }
            }
        },
        // 新增文件夹
        handleAddOrUpdateFolder(sign, node) {
            this.isAddOrUpdateFolder = true;
            this.$nextTick(() => {
                this.$refs["addOrUpdateFolderRef"].init(
                    sign,
                    node,
                    this.ownTreeData,
                    "account"
                );
            });
        },
        // 新增镜像
        handleAddModel(node) {
            this.isAddOrUpdateModel = true;
            this.$nextTick(() => {
                this.$refs["addOrUpdateModelRef"].init(undefined, node);
            });
        },
        // 点击树节点，右侧展示详细信息
        nodeClick(node) {
            if (node == undefined) {
                return;
            }
            this.selectedNodeInfo = node;
            this.currentNodeKey = node.id;
            this.$nextTick(() => {
                this.$refs.leftTreeRef.$refs.treeRef.setCurrentKey(this.currentNodeKey);
            });
            this.$store.commit("modelManageTool/SET_SELECTED_NODE_ID", {
                moduleName: "model",
                id: node.id,
            });
            if (!node.data) return;

            if (node.type == 0) {
                // 点击的文件夹
                this.isFolder = true;
                this.isModel = false;
                this.$store.commit("modelManageTool/SET_EXPANDED_NODE_IDS", {
                    moduleName: "model",
                    idList: Array.from(new Set([...this.defaultExpandedKeys, node.id])),
                });
            } else {
                // 点击的文件
                this.isFolder = false;
                this.isFile = true;
                this.isModel = true;
            }
        },
        /**
         * 树节点删除事件的回调
         * @param node 被删除的节点
         */
        handleNodeDelete(node) {
            this.$confirm(
                `确定删除${node.type == 0 ? "目录" : "镜像"}  ${node.data.name} ?`,
                "提示",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    customClass: "message-box-style",
                    type: "warning",
                }
            )
                .then(async () => {
                    const response = await deleteTreeApi(node.id);
                    if (response.code == 200) {
                        this.$message.success(
                            this.$toolHandle.getI18nName(
                                this.$zh.setup.responseText,
                                this.$en.setup.responseText,
                                this.$i18n.locale,
                                "success"
                            )
                        );
                        if (node.id == this.currentNodeKey) {
                            this.isFolder = false;
                            this.isModel = false;
                        }
                        this.getList();
                    }
                })
                .catch(() => { });
        },
        /**
         * 树节点复制事件的回调
         * @param node 被复制的节点
         */
        // handleCopyFile(node) {
        //   addModel({
        //     modelName: node.data.modelName + " Copy",
        //     modelEnglishName: node.data.modelEnglishName + " Copy",
        //     modelAlias: node.data.modelAlias + " Copy",
        //     parentId: node.data.parentId,
        //     nodeType: node.type, // 0表示文件夹，1表示文件
        //     categoryLabel: node.data.categoryLabel,
        //     modelResolution: node.data.modelResolution,
        //     modelDescription: node.data.modelDescription,
        //     modelType: node.data.modelType, // 0表示标准模型，1表示代理模型，2表示数字样机
        //     userId: node.data.userId,
        //   }).then((response) => {
        //     if (response.code == 200) {
        //       this.$message.success(
        //         this.$toolHandle.getI18nName(
        //           this.$zh.setup.responseText,
        //           this.$en.setup.responseText,
        //           this.$i18n.locale,
        //           "success"
        //         )
        //       );
        //       this.getList();
        //     }
        //   });
        // },
        // 移动树节点的顺序
        moveNodeOrder(draggingNode, dropNode, dropType) {
            moveTreeApi({
                movedNodeId: draggingNode.data.id, // 被移动节点的id
                referenceNodeId: dropNode.data.id, // 参照节点的id
                position: dropType == "after" ? 1 : dropType == "before" ? -1 : 0, // 相对位置，before:-1,into:0,after:1
                ancestors: draggingNode.data.data.ancestors, // 祖先
                folderChildrenOrder: {
                    parentId:
                        dropType == "inner" ? dropNode.data.id : dropNode.data.parentId, // 父级id
                    siblingIds:
                        dropType == "inner"
                            ? Array.from(dropNode.childNodes).map((item) => item.data.id)
                            : Array.from(dropNode.parent.childNodes).map(
                                (item) => item.data.id
                            ),
                },
            }).then((response) => {
                if (response.code == 200) {
                    this.$message.success(
                        this.$toolHandle.getI18nName(
                            this.$zh.setup.responseText,
                            this.$en.setup.responseText,
                            this.$i18n.locale,
                            "success"
                        )
                    );
                    this.getList();
                }
            });
        },
        // 点击菜单项触发的事件
        handleMenuClick(menu, node) {
            switch (menu.name) {
                case "新增镜像":
                    this.handleAddModel(node);
                    break;
                case "新增分类":
                    this.handleAddOrUpdateFolder("add");
                    break;
                case "添加子目录":
                    this.handleAddOrUpdateFolder("add", node);
                    break;
                case "编辑":
                    this.handleAddOrUpdateFolder("edit", node);
                    break;
                // case "复制":
                //   // 文件的复制
                //   this.handleCopyFile(node);
                //   break;
                case "删除":
                    // 文件夹/文件的删除
                    this.handleNodeDelete(node);
                    break;
            }
        },
    },
};
</script>

<style lang="scss" scoped>
.model-manage {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: row;

    .mm-panel-wrapper-left {
        width: 300px;
        height: 100%;
        flex-grow: 0;
        flex-shrink: 0;
        display: flex;
        position: relative;
        padding: 0 10px;
    }

    .mm-divider {
        width: 1px;
        height: auto;
        flex-grow: 0;
        position: relative;
        align-self: stretch;
        background-color: var(--ui-border-color-split);
    }

    .mm-panel-wrapper-right {
        width: 256px;
        height: 100%;
        min-width: 0px;
        flex-grow: 1;
        flex-shrink: 1;
        display: flex;
        position: relative;
        overflow: auto;
    }
}

.padding20 {
    padding: 20px;
    width: 100%;
}
</style>
